package com.acane.instagram.feature.login

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.acane.instagram.R
import com.acane.instagram.core.config.WebSocketManager
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.LightGrayBackground
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.feature.common.SessionManager
import kotlinx.coroutines.launch

@Composable
fun LoginScreen(
    toMain: () -> Unit,
    viewModel: LoginViewModel = viewModel(),
    toRegister: () -> Unit,
) {

    val loginState by viewModel.loginState.collectAsState()
// 监听登录状态变化
    LaunchedEffect(loginState) {
        when (loginState) {
            is LoginViewModel.LoginState.Success -> {
                // 登录成功后
                WebSocketManager.connect(SessionManager._sessionId!!)
                toMain()
            }
            else -> {}
        }
    }

    var inputUserName by remember { mutableStateOf("") }
    var inputPassword by remember { mutableStateOf("") }
    var showSnackbar by remember { mutableStateOf(false) }

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
        modifier = Modifier.padding(16.dp)
    ) {
        // LOGO
        LOGO()
        // 账号密码输入区域
        LoginInput(
            inputUserName = inputUserName,
            onUserNameChange = { inputUserName = it },
            inputPassword = inputPassword,
            onPasswordChange = { inputPassword = it }
        )
        // 忘记密码文本
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 10.dp),
            horizontalArrangement = Arrangement.End
        ) {
            androidx.compose.material3.Text(
                text = "忘记密码了？",
                color = InstagramBlue,
                fontSize = 14.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.clickable { /* 忘记密码处理 */ }
            )
        }
        // 登录按钮
        LoginButton(
            inputUserName = inputUserName,
            inputPassword = inputPassword,
            onLoginSuccess = { user ->
                //userInfo = user
                //loginManager.saveUserInfo(user)
            },
            onLoginFailure = { showSnackbar = true },
            viewModel = viewModel,
            toMain = toMain,
        )
        Spacer(modifier = Modifier.weight(1.0f))

        // 分割线
        Divider(modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 20.dp))
        // 注册文本按钮
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 10.dp),
            horizontalArrangement = Arrangement.Center
        ) {
            androidx.compose.material3.Text(
                text = "还没有帐户？",
                color = InstagramDarkGray,
                fontSize = 14.sp,
                fontWeight = FontWeight.Bold
            )
            Spacer(modifier = Modifier.size(8.dp))
            androidx.compose.material3.Text(
                text = "注册",
                color = InstagramBlue,
                fontSize = 14.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.clickable {
                    toRegister()
                }
            )
        }
    }
}


@Composable
fun LoginRoute(
    toMain: () -> Unit,
    toRegister: () -> Unit,
) {
    //val viewModelStoreOwner = LocalViewModelStoreOwner.current ?: error("No ViewModelStoreOwner provided")
   LoginScreen(
       toMain = toMain,
       toRegister = toRegister,
   )
}



@Composable
fun LoginButton(
    inputUserName: String,
    inputPassword: String,
    onLoginSuccess: (UserInfo) -> Unit,
    onLoginFailure: () -> Unit,
    viewModel: LoginViewModel,
    toMain: () -> Unit
) {
    // 键盘控制器
    val keyboardController = LocalSoftwareKeyboardController.current
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    androidx.compose.material3.Button(
        onClick = {
            if (inputPassword.isBlank() || inputUserName.isBlank()) {
                // 提示不能为空
                Toast.makeText(context, "帐户或密码不能为空", Toast.LENGTH_SHORT).show()
            }
            Log.d("LoginButton", "点击登录（协程外）") // 先验证这里能否打印
            coroutineScope.launch {
                Log.d("LoginButton", "协程启动") // 验证协程是否正常启动
                val userResponse = viewModel.login(inputUserName, inputPassword, toMain)
                // 提示登录结果
                if (userResponse != null) {
                    keyboardController?.hide()
                    Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(context, "帐户或密码错误", Toast.LENGTH_SHORT).show()
                }
            }
        },
        colors = ButtonDefaults.buttonColors(
            containerColor = InstagramBlue,
            contentColor = Color.White
        ),
        modifier = Modifier
            .height(60.dp)
            .padding(horizontal = 8.dp)
            .fillMaxWidth(),
        shape = RoundedCornerShape(5.dp),
        elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
        contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
    ) {
        androidx.compose.material3.Text(
            text = "登录",
            fontSize = 16.sp,
            color = Color.White,
            fontWeight = FontWeight.Bold
        )
    }
}

@Composable
fun LoginInput(
    inputUserName: String,
    onUserNameChange: (String) -> Unit,
    inputPassword: String,
    onPasswordChange: (String) -> Unit
) {
    var isPasswordVisible by remember { mutableStateOf(false) }
    Column(
        modifier = Modifier.padding(start = 8.dp, end = 8.dp)
    ) {
        // 账号
        TextField(
            value = inputUserName,
            onValueChange = onUserNameChange,
            placeholder = {
                androidx.compose.material3.Text(
                    text = "手机号、账号或邮箱",
                    color = InstagramDarkGray,
                    fontSize = 14.sp
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp)
                .heightIn(min = 48.dp, max = 56.dp),
            colors = TextFieldDefaults.colors(
                focusedIndicatorColor = LightGrayBackground,
                unfocusedIndicatorColor = LightGrayBackground,
                disabledIndicatorColor = LightGrayBackground,
                unfocusedContainerColor = LightGrayBackground,
            ),
            shape = RoundedCornerShape(5.dp),
        )
        Spacer(modifier = Modifier.size(10.dp))
        // 密码
        TextField(
            value = inputPassword,
            onValueChange = onPasswordChange,
            placeholder = {
                androidx.compose.material3.Text(
                    text = "密码",
                    color = InstagramDarkGray,
                    fontSize = 14.sp
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp)
                .heightIn(min = 48.dp, max = 56.dp),
            colors = TextFieldDefaults.colors(
                focusedIndicatorColor = LightGrayBackground,
                unfocusedIndicatorColor = LightGrayBackground,
                disabledIndicatorColor = LightGrayBackground,
                unfocusedContainerColor = LightGrayBackground,
            ),
            shape = RoundedCornerShape(5.dp),
            visualTransformation = if (isPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),
            trailingIcon = {
                val image = if (isPasswordVisible) R.drawable.eye else R.drawable.eye_hide
                IconButton(onClick = { isPasswordVisible = !isPasswordVisible }) {
                    Icon(
                        painter = painterResource(id = image),
                        contentDescription = if (isPasswordVisible) "Hide Password" else "Show Password",
                        tint = Color.Unspecified,
                        modifier = Modifier.size(25.dp)
                    )
                }
            }
        )
    }
}

@Composable
fun LOGO() {
    Image(
        painter = painterResource(id = R.drawable.ins),
        contentDescription = "logo",
        modifier = Modifier
            .size(200.dp)
            .padding(top = 50.dp)
    )
}
